import React, { useState, useEffect } from 'react'
import { Card, Select, Form, Modal, Pagination, Input, Row, Col, Button, Table, message, Switch, Tooltip, Space } from 'antd'
import { EditOutlined, ExclamationCircleOutlined,DeleteOutlined, ApartmentOutlined } from '@ant-design/icons'
import { getUsersListAPI, addUserAPI, editUserAPI, deleteUserAPI } from '../../app/user'
import { getRolesListAPI, dispatchRoleAPI } from '../../app/roles'
import './index.less'

const { Search  } = Input
const { confirm } = Modal
const { Option } = Select
export default function Users () {
    // 创建不同的form表单实例
    const [addForm] = Form.useForm()
    const [editForm] = Form.useForm()

    // 定义用户列表数据
    const [userList, setUserList] = useState([])

    // 定义用户列表数据总条数
    const [userTotal, setUserTotal] = useState(0)

    // 定义用户数据查询参数对象
    const [queryInfo, setQueryInfo] = useState({query:'', pagenum:1, pagesize:2})

    // 添加用户控制显示弹框
    const [isAddVisible, setIsAddVisible] = useState(false)

    // 点击确认按钮处于loading状态
    const [confirmLoading, setConfirmLoading] = useState(false)

    // 编辑用户控制显示弹框
    const [isEditVisible, setIsEditVisible] = useState(false)

    // 分配角色控制显示弹框
    const [isDispatchVisible, setIsDispatchVisible] = useState(false)

    // 编辑用户所在行的基本信息
    const [editInfo, setEditInfo] = useState({})

    // 分配角色所在行的基本信息
    const [dispatchInfo, setDispatchInfo] = useState({})

    // 角色列表
    const [rolesList, setRolesList] = useState([])

    // 请求用户列表数据
    const loadUserList = async () => {
      // 发请求，获取用户列表数据
      const {data, meta} = await getUsersListAPI(queryInfo)
      if(meta.status !== 200) return message.error('获取用户列表数据失败')
      // 给每一个需要渲染的数据加上key
      data.users.forEach((item, index) => item.key = index)
      setUserList(data.users)
      setUserTotal(data.total)
    }

    // 发起请求获取列表数据
    useEffect(() => {
      loadUserList()
    }, [queryInfo])

    // 定义增加用户弹框的校验规则
    const addUserRules = {
      username:[
        { required: true, message: '请输入用户名称' },
        { min:3, max:10, message:'用户名在3~10个字符之间' }
      ],
      password:[
        { required: true, message: '请输入密码' },
        { min:6, max:15, message:'用户名在6~15个字符之间' }
      ],
      email:[
        { required: true, message: '请输入邮箱' },
        { pattern:/^\w+@\w+(\.\w+)+$/, message: '请输入合法的邮箱'}
      ],
      mobile:[
        { required: true, message: '请输入手机号码' },
        { pattern:/^1[34578]\d{9}$/, message: '请输入合法手机号码' }
      ]
    }
    // 搜索，获取数据
    const onSearch = query => setQueryInfo(e => ({...e, query}))
    // 鼠标按下触发搜索
    const onKeyDownSearch = e => onSearch(e.target.value)

    // 分页器改变
    const paginationChange = (pagenum, pagesize) => setQueryInfo(e => ({...e, pagenum, pagesize}))

    // 显示添加用户弹框
    const addUser = () => {
      addForm.resetFields()
      setIsAddVisible(true)
    }
    // 确认点击添加用户
    const onConfirmAddUser = () => {
      addForm.validateFields()
      .then(async values => {
        const { meta } = await addUserAPI(values)
        if(meta.status !== 201) return message.error('添加用户失败')
        loadUserList()
        setIsAddVisible(false)
        message.success('添加用户成功')
      })
      .catch(() => {
        message.error('用户信息校验不通过')
      })

    }
    // 取消添加用户
    const onCancelAddUser = () => {
      setIsAddVisible(false)
    }

    // 显示编辑用户弹框
    const editUser = (record) => {
      // console.log(record)
      setEditInfo(record)
      editForm.setFieldsValue(record)
      setIsEditVisible(true)
    }
    // 确认点击编辑用户
    const onConfirmEditUser = () => {
      setConfirmLoading(true)
      editForm.validateFields()
      .then(async values => {
        const { data, meta } = await editUserAPI({...editInfo, ...values})
        if(meta.status !== 200) {
          setConfirmLoading(false)
          return message.error('编辑用户失败')
        }
        setUserList(perVal =>
          perVal.map(item => {
            if(item.id === data.id) {
              data.key = item.key
              return {...item, ...data}
            }
            return item
          })
        )
        setConfirmLoading(false)
        setIsEditVisible(false)
        message.success('编辑用户成功')
      })
      .catch(() => {
        setConfirmLoading(false)
        message.error('请按规范填写数据')
      })

    }
    // 取消编辑用户
    const onCancelEditUser = () => {
      editForm.resetFields()
      setEditInfo({})
      setIsEditVisible(false)
    }

    // 显示删除用户弹框
    const deleteUser = (userId) => {
        confirm({
          title: '此操作将永久删除该用户!',
          icon: <ExclamationCircleOutlined />,
          content: '是否继续?',
          okText: '确认',
          cancelText: '取消',
          async onOk () {
            const { meta } = await deleteUserAPI(userId)
            if(meta.status !== 200) return message.error('删除用户失败')
            message.success('删除用户成功')
            loadUserList()
          },
          onCancel() {
            message.info('已取消删除')
          }
        })

    }

    // 分配角色
    const dispatchRoles = (record) => {
      setDispatchInfo(record)
      setIsDispatchVisible(true)
    }
    // 确认点击分配角色
    const onConfirmDispatchRoles = async () => {
      const {id, rid} = dispatchInfo
      setConfirmLoading(true)
      const { meta } = await dispatchRoleAPI(id, rid)
      if(meta.status !== 200) {
        setConfirmLoading(false)
        return message.error('设置角色失败')
      }
      message.success('设置角色成功')
      setConfirmLoading(false)
      setIsDispatchVisible(false)
    }
    // 取消点击分配角色
    const onCancelDispatchRoles = () => {
      setIsDispatchVisible(false)
    }
    // 下拉框数据改变获取值
    const handleRoleChange = value => {
      setDispatchInfo(e => ({...e, rid:value}))
    }
    // 展开下拉选择框，获取数据
    const onDropdownVisible = async () => {
      const { data, meta } = await getRolesListAPI()
      if(meta.status !== 200) return message.error('获取角色列表失败')
      setRolesList(data)
    }
    // 表格每一列标题
    const columns = [
      {
        title: '#',
        dataIndex: 'key',
        key:'key'
      },
      {
        title: '姓名',
        dataIndex: 'username',
        key:'username'
      },
      {
        title: '邮箱',
        dataIndex: 'email',
        key:'email'
      },
      {
        title: '电话',
        dataIndex: 'mobile',
        key:'mobile'
      },
      {
        title: '角色',
        dataIndex: 'role_name',
        key:'role_name'
      },
      {
        title: '状态',
        dataIndex: 'mg_state',
        key:'mg_state',
        render:text => {
          const component = <Switch checked={text} />
          return component
        }
      },
      {
        title: '操作',
        dataIndex: 'operation',
        key:'operation',
        render:(_, record) => {
          const component = <>
          <Space>
            <Button key="1" type="primary" onClick={() => editUser(record)} icon={<EditOutlined />}>
            </Button>
            <Button key="2" type="danger" onClick={() => deleteUser(record.id)} icon={<DeleteOutlined />}>
            </Button>
            <Tooltip key="3" title="分配角色">
              <Button  icon={<ApartmentOutlined />} className="allocate-roles" onClick={() => dispatchRoles(record)} />
            </Tooltip>
          </Space>
          </>
          return component
        }
      }
    ]
    return (
        <Card className="user-container">
            {/* 搜索 */}
            <Row>
                <Col span={12}>
                    <Search onPressEnter={onKeyDownSearch} onSearch={onSearch} placeholder="请输入内容" />
                </Col>
                <Col span={4}>
                    <Button onClick={addUser} type="primary" className="add-user-btn">添加用户</Button>
                </Col>
            </Row>
            {/* table表格 */}
            <Table
                bordered
                columns={columns}
                dataSource={userList}
                pagination={false}
            />
            {/* 分页 */}
            <Pagination
                total={userTotal}
                showTotal={total => `总共 ${total} 条`}
                defaultPageSize={queryInfo.pagesize}
                current={queryInfo.pagenum}
                pageSizeOptions={[2,4,8,10]}
                onChange={paginationChange}
                showSizeChanger
            />
            {/* 增加用户弹框 */}
            <Modal cancelText="取消" okText="确定"  width={800} title="添加用户" visible={isAddVisible} onOk={onConfirmAddUser} onCancel={onCancelAddUser}>
              <Form form={addForm} labelCol={{span:2}}>
                  <Form.Item
                      label="用户名"
                      name="username"
                      rules={addUserRules.username}
                  >
                    <Input />
                  </Form.Item>
                  <Form.Item
                      label="密码"
                      name="password"
                      rules={addUserRules.password}
                  >
                    <Input type="password" />
                  </Form.Item>
                  <Form.Item
                      label="邮箱"
                      name="email"
                      rules={addUserRules.email}
                  >
                    <Input />
                  </Form.Item>
                  <Form.Item
                      label="手机"
                      name="mobile"
                      rules={addUserRules.mobile}
                  >
                    <Input />
                  </Form.Item>
              </Form>
            </Modal>
            {/* 编辑用户弹框 */}
            {/* 踩坑，给Form添加默认值会出现数据更新不及时,要使用setFieldsValue(对象) */}
            <Modal  cancelText="取消" okText="确定"  width={800} title="编辑用户" visible={isEditVisible} onOk={onConfirmEditUser} onCancel={onCancelEditUser} confirmLoading={confirmLoading}>
              {
                <Form
                    form={editForm}
                    labelCol={{span:2}}
                    initialValues={{
                      username:editInfo.username,
                      email:editInfo.email,
                      mobile:editInfo.mobile
                    }}
                >
                  <Form.Item label="用户名" name="username">
                    <Input disabled />

                  </Form.Item>
                  <Form.Item label="邮箱" name="email" rules={addUserRules.email}>
                    <Input />

                  </Form.Item>
                  <Form.Item label="手机" name="mobile" rules={addUserRules.mobile} >
                    <Input />

                  </Form.Item>
              </Form>
              }
            </Modal>
            {/* 删除用户弹框 */}
            {/* 分配角色弹框 */}
            <Modal
                title="分配角色"
                cancelText="取消"
                okText="确定"
                visible={isDispatchVisible}
                onOk={onConfirmDispatchRoles}
                onCancel={onCancelDispatchRoles}
                confirmLoading={confirmLoading}
            >
              <Row>
                <Col>当前用户：</Col>
                <Col>{dispatchInfo.username}</Col>
              </Row>
              <Row>
                <Col>当前角色：</Col>
                <Col>{dispatchInfo.role_name}</Col>
              </Row>
              <Row>
                <Col>分配新角色：</Col>
                <Col>
                <Select
                    onFocus={onDropdownVisible}
                    placeholder="请选择"
                    style={{ width: 200 }}
                    onChange={handleRoleChange}
                >
                  {
                    rolesList.map(item => {
                      return <Option key={item.id} value={item.id}>{item.roleName}</Option>
                    })
                  }
                </Select>
                </Col>
              </Row>
            </Modal>
        </Card>
    )
}
